package com.yidian.controller.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yidian.pojo.system.Admin;
import com.yidian.pojo.system.Resource;
import com.yidian.server.system.AdminService;
import com.yidian.server.system.ResourceService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author whb
 * @create 2021-06-08 15:25
 * @desciption 使用UserDetailsService配置SpringSecurity认证
 */
public class UserDetailsServiceImpl implements UserDetailsService {
    @Reference
    private AdminService adminService;
    @Reference
    private ResourceService resourceService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("经过UserDetailsServiceImpl实现安全认证..");

        //查询系统管理员
        Map<String, Object> searchMap = new HashMap<>();
        searchMap.put("loginName", username);
        List<Admin> adminList = adminService.findList(searchMap);

        if (adminList.size() == 0) {
            return null;
        }

        //构建角色集合，根据用户信息查询用户角色集合
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        //grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        List<Resource> resourceList = resourceService.findResourceByLoginName(username);
        if (resourceList.size()>0){
            for (Resource resource:resourceList){
                grantedAuthorities.add(new SimpleGrantedAuthority(resource.getResKey()));
            }
        }
        return new User(username, adminList.get(0).getPassword(), grantedAuthorities);
    }
}
